import { COLORS, PIECE_VALUES, AI_DIFFICULTY } from './constants.js';

// AI类
export class ChessAI {
    constructor(difficulty = AI_DIFFICULTY.EASY) {
        this.difficulty = difficulty;
        this.maxDepth = this.getMaxDepth();
    }
    
    // 根据难度设置搜索深度
    getMaxDepth() {
        switch (this.difficulty) {
            case AI_DIFFICULTY.EASY:
                return 2;
            case AI_DIFFICULTY.MEDIUM:
                return 3;
            case AI_DIFFICULTY.HARD:
                return 4;
            default:
                return 2;
        }
    }
    
    // 设置难度
    setDifficulty(difficulty) {
        this.difficulty = difficulty;
        this.maxDepth = this.getMaxDepth();
    }
    
    // 选择最佳移动
    chooseMove(board, color) {
        console.log(`AI正在思考下一步棋... (难度: ${this.difficulty}, 搜索深度: ${this.maxDepth})`);
        
        const startTime = Date.now();
        const { bestMove } = this.minimax(board, this.maxDepth, -Infinity, Infinity, color === COLORS.BLACK);
        const endTime = Date.now();
        
        console.log(`AI思考完成，耗时: ${endTime - startTime}ms`);
        
        return bestMove;
    }
    
    // 极小化极大算法（带Alpha-Beta剪枝）
    minimax(board, depth, alpha, beta, isMaximizingPlayer) {
        // 到达搜索深度或游戏结束
        if (depth === 0) {
            return { score: this.evaluateBoard(board), bestMove: null };
        }
        
        // 检查游戏状态
        if (board.isCheckmated(isMaximizingPlayer ? COLORS.BLACK : COLORS.RED)) {
            return { score: isMaximizingPlayer ? -Infinity : Infinity, bestMove: null };
        }
        
        if (board.isDraw()) {
            return { score: 0, bestMove: null };
        }
        
        const currentColor = isMaximizingPlayer ? COLORS.BLACK : COLORS.RED;
        let bestMove = null;
        let bestScore = isMaximizingPlayer ? -Infinity : Infinity;
        
        // 获取所有可能的移动
        const allPossibleMoves = this.getAllPossibleMoves(board, currentColor);
        
        // 对移动进行排序，优先考虑吃子和重要位置
        allPossibleMoves.sort((a, b) => this.moveSortScore(b, board) - this.moveSortScore(a, board));
        
        // 遍历所有可能的移动
        for (const move of allPossibleMoves) {
            // 模拟移动
            const clonedBoard = board.clone();
            const capturedPiece = clonedBoard.movePiece(move.fromRow, move.fromCol, move.toRow, move.toCol);
            
            // 递归评估
            const result = this.minimax(clonedBoard, depth - 1, alpha, beta, !isMaximizingPlayer);
            const currentScore = result.score;
            
            // 更新最佳分数和移动
            if (isMaximizingPlayer) {
                if (currentScore > bestScore) {
                    bestScore = currentScore;
                    bestMove = move;
                }
                alpha = Math.max(alpha, currentScore);
            } else {
                if (currentScore < bestScore) {
                    bestScore = currentScore;
                    bestMove = move;
                }
                beta = Math.min(beta, currentScore);
            }
            
            // Alpha-Beta剪枝
            if (beta <= alpha) {
                break;
            }
        }
        
        return { score: bestScore, bestMove };
    }
    
    // 获取所有可能的移动
    getAllPossibleMoves(board, color) {
        const moves = [];
        
        for (let row = 0; row < 10; row++) {
            for (let col = 0; col < 9; col++) {
                const piece = board.getPieceAt(row, col);
                if (piece && piece.color === color) {
                    const possibleMoves = piece.getPossibleMoves(board);
                    
                    possibleMoves.forEach(move => {
                        moves.push({
                            fromRow: row,
                            fromCol: col,
                            toRow: move.row,
                            toCol: move.col,
                            piece: piece
                        });
                    });
                }
            }
        }
        
        return moves;
    }
    
    // 评估棋盘分数
    evaluateBoard(board) {
        let score = 0;
        
        // 评估每个棋子的价值和位置
        for (let row = 0; row < 10; row++) {
            for (let col = 0; col < 9; col++) {
                const piece = board.getPieceAt(row, col);
                if (piece) {
                    const pieceValue = PIECE_VALUES[piece.type];
                    const positionValue = this.getPositionValue(piece, row, col);
                    const colorFactor = piece.color === COLORS.BLACK ? 1 : -1;
                    
                    score += colorFactor * (pieceValue + positionValue);
                }
            }
        }
        
        // 评估将军威胁
        if (board.isInCheck(COLORS.RED)) {
            score += 300; // 黑方将军，加分
        }
        if (board.isInCheck(COLORS.BLACK)) {
            score -= 300; // 红方将军，减分
        }
        
        // 评估棋子移动自由度
        const blackMobility = this.getAllPossibleMoves(board, COLORS.BLACK).length;
        const redMobility = this.getAllPossibleMoves(board, COLORS.RED).length;
        score += (blackMobility - redMobility) * 10;
        
        return score;
    }
    
    // 获取位置价值（位置评分表）
    getPositionValue(piece, row, col) {
        // 对于不同颜色，反转行坐标
        const adjustedRow = piece.color === COLORS.BLACK ? row : 9 - row;
        
        // 位置评分表（简化版）
        const positionTables = {
            'rook': [
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [5, 10, 10, 10, 10, 10, 10, 10, 5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [0, 0, 0, 5, 15, 5, 0, 0, 0]
            ],
            'horse': [
                [-10, -5, -5, -5, -5, -5, -5, -5, -10],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 5, 10, 10, 10, 5, 0, -5],
                [-5, 5, 5, 10, 10, 10, 5, 5, -5],
                [-5, 0, 10, 10, 10, 10, 10, 0, -5],
                [-5, 10, 10, 10, 10, 10, 10, 10, -5],
                [-5, 5, 0, 0, 0, 0, 0, 5, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-10, -5, -5, -5, -5, -5, -5, -5, -10]
            ],
            'elephant': [
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, 10, -5, 10, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, 10, -5, 5, -5, 10, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, 10, -5, 10, -5, -5, -5]
            ],
            'advisor': [
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, 10, -5, 10, -5, -5, -5],
                [-5, -5, -5, -5, 20, -5, -5, -5, -5],
                [-5, -5, -5, 10, -5, 10, -5, -5, -5]
            ],
            'general': [
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, -5, -5, -5, -5, -5],
                [-5, -5, -5, -5, 10, -5, -5, -5, -5],
                [-5, -5, -5, 10, 20, 10, -5, -5, -5],
                [-5, -5, -5, -5, 10, -5, -5, -5, -5]
            ],
            'cannon': [
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [5, 0, 0, -10, -10, -10, 0, 0, 5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [-5, 0, 0, 0, 0, 0, 0, 0, -5],
                [5, 10, 10, 10, 10, 10, 10, 10, 5],
                [5, 0, 0, 0, 0, 0, 0, 0, 5],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0]
            ],
            'pawn': [
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [50, 50, 50, 50, 50, 50, 50, 50, 50],
                [10, 10, 20, 30, 30, 30, 20, 10, 10],
                [5, 5, 10, 25, 25, 25, 10, 5, 5],
                [0, 0, 0, 20, 20, 20, 0, 0, 0],
                [5, -5, -10, 0, 0, 0, -10, -5, 5],
                [5, 10, 10, -20, -20, -20, 10, 10, 5],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0]
            ]
        };
        
        const table = positionTables[piece.type];
        if (table && table[adjustedRow] && table[adjustedRow][col] !== undefined) {
            return table[adjustedRow][col];
        }
        
        return 0;
    }
    
    // 移动排序评分（用于优化Alpha-Beta剪枝）
    moveSortScore(move, board) {
        let score = 0;
        
        // 吃子评分
        const capturedPiece = board.getPieceAt(move.toRow, move.toCol);
        if (capturedPiece) {
            score += PIECE_VALUES[capturedPiece.type] - PIECE_VALUES[move.piece.type];
        }
        
        // 将军评分
        const clonedBoard = board.clone();
        clonedBoard.movePiece(move.fromRow, move.fromCol, move.toRow, move.toCol);
        const opponentColor = move.piece.color === COLORS.BLACK ? COLORS.RED : COLORS.BLACK;
        if (clonedBoard.isInCheck(opponentColor)) {
            score += 200;
        }
        
        // 保护己方将/帅
        const general = board.findGeneral(move.piece.color);
        if (general) {
            const distanceToGeneral = Math.abs(move.toRow - general.row) + Math.abs(move.toCol - general.col);
            score += (10 - distanceToGeneral) * 5;
        }
        
        return score;
    }
    
    // 简单难度的AI（直接随机选择移动）
    chooseEasyMove(board, color) {
        const possibleMoves = this.getAllPossibleMoves(board, color);
        if (possibleMoves.length === 0) {
            return null;
        }
        
        // 优先选择吃子的移动
        const captureMoves = possibleMoves.filter(move => 
            board.getPieceAt(move.toRow, move.toCol) !== null
        );
        
        if (captureMoves.length > 0) {
            return captureMoves[Math.floor(Math.random() * captureMoves.length)];
        }
        
        // 否则随机选择一个移动
        return possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
    }
    
    // 中等难度AI（有限深度搜索）
    chooseMediumMove(board, color) {
        this.maxDepth = 3;
        return this.chooseMove(board, color);
    }
    
    // 困难难度AI（更深深度搜索）
    chooseHardMove(board, color) {
        this.maxDepth = 4;
        return this.chooseMove(board, color);
    }
}